package graphics.screens.playlists;

import files.Files;
import function.search.EventListener;
import graphics.SearchChoiceInput2;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;

import boot.Boot;

public class PlaylistListScreen extends Canvas implements CommandListener {

	private static final String PLAYLIST_EXTENSION = "*.pdb";

	private final Command cancelCommand = new Command("Cancel", Command.EXIT, 1);

	private SearchChoiceInput2 playlistChoiceInput;
	private String[] playlists;

	public PlaylistListScreen() {
		addCommand(cancelCommand);
		setCommandListener(this);
		reboot();
	}

	protected void paint(Graphics g) {

		playlistChoiceInput.repaint(g);
	}

	public void commandAction(Command command, Displayable dis) {
		if (command == cancelCommand) {
			Boot.getInstance().readyToGo();
		}
	}

	public void keyPressed(int keyCode) {

		playlistChoiceInput.keyPressed(keyCode);
		repaint();
	}

	public void reboot() {
		setupPlaylists();
		playlistChoiceInput = new SearchChoiceInput2(playlists);
		playlistChoiceInput.addListener(new PlaylistChoiceListener());
	}

	private void setupPlaylists() {
		try {
			FileConnection fc = (FileConnection) Connector
					.open(Files.PLAYLIST_PATH);
			Enumeration e = fc.list(PLAYLIST_EXTENSION, true);
			int count = 0;

			while (e.hasMoreElements()) {
				e.nextElement();
				count++;
			}

			playlists = new String[count];
			e = fc.list(PLAYLIST_EXTENSION, true);
			int index = 0;

			while (e.hasMoreElements()) {
				String fileName = (String) e.nextElement();
				String title = fileName.substring(0, fileName.lastIndexOf('.'));
				playlists[index] = title;
				index++;
			}
			fc.close();
		} catch (IOException e) {
			Boot.alertException(e, this, "setupPlaylists()");
		}
	}

	private class PlaylistChoiceListener implements EventListener {

		public void processEvent(String event) {
			int chosenIndex = playlistChoiceInput.getchosenIndex();
			String chosen = playlists[chosenIndex];
			Boot.playPlaylist(chosen);
			reboot();
		}

	}
}
